<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>使用工具安装，运行，停止，卸载Window服务 - 焰尾迭 - 博客园</title>
<link type="text/css" rel="stylesheet" href="/bundles/blog-common.css?v=Jsknfrse2BShd-7DrxM42RyulObn44e4JjkI6-WX6zk1"/>
<link id="MainCss" type="text/css" rel="stylesheet" href="/skins/nature/bundle-nature.css?v=SMSmqROZamyrz003uRLsZZQqisVE_ymEDyPy07GKHPw1"/>
<link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/yanweidie/rss"/>
<link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/yanweidie/rsd.xml"/>
<link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/yanweidie/wlwmanifest.xml"/>
<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script>  
<script type="text/javascript">var currentBlogApp = 'yanweidie', cb_enable_mathjax=false;</script>
<script src="/bundles/blog-common.js?v=V3tkfsuahqfUzgmqZVwj2QjsxodIvgDfvPKdn8yDuMY1" type="text/javascript"></script>
</head>
<body>
<a name="top"></a>
<!--PageBeginHtml Block Begin-->
<link href="http://files.cnblogs.com/yanweidie/main.css" rel="stylesheet" type="text/css" />
<!--PageBeginHtml Block End-->

<!--done-->
<div id="banner"><div id="bnr_pic">
<!--done-->
<div class="header">
	<div class="headerText">
		<a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/yanweidie/">焰尾迭</a><br>
	</div><br>
	<div class="headerDis">吾生也有涯，而知也无涯。以有涯随无涯，殆已。</div>
</div>
</div></div>
<div id="main">
	<!-- left starts -->
	<div id="left">
		<DIV id="mystats">
			<br/>
				
<!--done-->
<div class="blogStats">
随笔 - 30&nbsp;
文章 - 0&nbsp;
评论 - 523&nbsp;

</div>
			
		</DIV>
		<div id="mylinks">
<!--done-->
<a id="MyLinks1_HomeLink" class="menu" href="http://www.cnblogs.com/">博客园</a>&nbsp;&nbsp;<a id="MyLinks1_MyHomeLink" class="menu" href="http://www.cnblogs.com/yanweidie/">首页</a>&nbsp;&nbsp;<a id="MyLinks1_NewPostLink" class="menu" rel="nofollow" href="http://i.cnblogs.com/EditPosts.aspx?opt=1">新随笔</a>&nbsp;&nbsp;<a id="MyLinks1_ContactLink" accesskey="9" class="menu" rel="nofollow" href="http://msg.cnblogs.com/send/%E7%84%B0%E5%B0%BE%E8%BF%AD">联系</a>&nbsp;&nbsp;<a id="MyLinks1_Admin" class="menu" rel="nofollow" href="http://i.cnblogs.com/">管理</a>&nbsp;&nbsp;<a id="MyLinks1_Syndication" class="menu" href="http://www.cnblogs.com/yanweidie/rss">订阅</a>&nbsp;<a id="MyLinks1_XMLLink" href="http://www.cnblogs.com/yanweidie/rss"><img src="http://www.cnblogs.com/images/xml.gif" alt="订阅" /></a></div>
		<div id="topics">
			
<div id="post_detail">
<div class="post">
	<div class="postTitle">
		<h1><a id="cb_post_title_url" class="postTitle2" href="http://www.cnblogs.com/yanweidie/p/3542670.html">使用工具安装，运行，停止，卸载Window服务</a></h1>
	</div>
	<div id="cnblogs_post_body"><p>&nbsp;</p>
<h1 style="background-color: #a5a5a5; color: white; font-size: 22px;">WSWinForm.exe介绍</h1>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; WSWinForm.exe是我自己开发的一个实用的小工具，用于将任何EXE程序作为Windows服务运行。也就是说WSWinForm只是其注册程序的服务外壳，这个特性对于我们来说非常实用，我们可以通过它来安装，运行，停止，卸载Windows服务，而不再是通过命令行InstallUtil的方式来安装。</p>
<h1 style="background-color: #a5a5a5; color: white; font-size: 22px;">资源下载</h1>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 你可以通过本文下载。</p>
<p>　　<a href="http://files.cnblogs.com/yanweidie/Windows%E6%9C%8D%E5%8A%A1%E5%AE%89%E8%A3%85%E4%B8%8E%E5%8D%B8%E8%BD%BD.rar" target="_blank">应用程序</a></p>
<p>　　<a href="http://files.cnblogs.com/yanweidie/WSWinForm.rar" target="_blank">源代码</a></p>
<p>　　<a href="http://www.cnblogs.com/yanweidie/p/3564062.html" target="_blank">最新版本信息查看</a></p>
<p>　　GitHub地址：<a href="https://github.com/CrazyJson/TaskManager" target="_blank">https://github.com/CrazyJson/TaskManager</a></p>
<p>　　SVN地址：<a href="http://code.taobao.org/svn/TaskManagerPub/Branch" target="_blank">http://code.taobao.org/svn/TaskManagerPub/Branch</a></p>
<h1 style="background-color: #a5a5a5; color: white; font-size: 22px;">如何使用</h1>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 下载完软件以后，我们能干些什么呢？看看这个截图吧：。</p>
<p>&nbsp;<img src="http://images.cnitblog.com/blog/336693/201402/101359502434254.png" alt="" /></p>
<p>这里可以看到的操作：</p>
<p>1. 安装指定路径的服务，</p>
<p>2. 运行指定服务，</p>
<p>3. 停止正在运行的服务，</p>
<p>4. 卸载服务，</p>
<p>这些功能是怎么通过代码来实现的呢，我后面再说。先对它有个印象就可以了。</p>
<h1 style="background-color: #a5a5a5; color: white; font-size: 22px;">代码解析</h1>
<p><strong>1.安装功能：</strong></p>
<div class="cnblogs_code" onclick="cnblogs_code_show('f16e5ca5-f789-4020-a411-619137081ecb')"><img id="code_img_closed_f16e5ca5-f789-4020-a411-619137081ecb" class="code_img_closed" src="http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt="" /><img id="code_img_opened_f16e5ca5-f789-4020-a411-619137081ecb" class="code_img_opened" style="display: none;" onclick="cnblogs_code_hide('f16e5ca5-f789-4020-a411-619137081ecb',event)" src="http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="" />
<div id="cnblogs_code_open_f16e5ca5-f789-4020-a411-619137081ecb" class="cnblogs_code_hide">
<pre><span style="color: #008080;"> 1</span>                 <span style="color: #0000ff;">string</span>[] cmdline =<span style="color: #000000;"> { };
</span><span style="color: #008080;"> 2</span>                 <span style="color: #0000ff;">string</span> serviceFileName =<span style="color: #000000;"> txtPath.Text.Trim();
</span><span style="color: #008080;"> 3</span>                 <span style="color: #0000ff;">string</span> serviceName =<span style="color: #000000;"> GetServiceName(serviceFileName);
</span><span style="color: #008080;"> 4</span>                 <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">string</span><span style="color: #000000;">.IsNullOrEmpty(serviceName))
</span><span style="color: #008080;"> 5</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 6</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">指定文件不是Windows服务！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;"> 7</span>                     <span style="color: #0000ff;">return</span><span style="color: #000000;">;
</span><span style="color: #008080;"> 8</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 9</span>                 <span style="color: #0000ff;">if</span><span style="color: #000000;"> (ServiceIsExisted(serviceName))
</span><span style="color: #008080;">10</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">11</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">要安装的服务已经存在！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">12</span>                     <span style="color: #0000ff;">return</span><span style="color: #000000;">;
</span><span style="color: #008080;">13</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">14</span>                 TransactedInstaller transactedInstaller = <span style="color: #0000ff;">new</span><span style="color: #000000;"> TransactedInstaller();
</span><span style="color: #008080;">15</span>                 AssemblyInstaller assemblyInstaller = <span style="color: #0000ff;">new</span><span style="color: #000000;"> AssemblyInstaller(serviceFileName, cmdline);
</span><span style="color: #008080;">16</span> <span style="color: #000000;">                transactedInstaller.Installers.Add(assemblyInstaller);
</span><span style="color: #008080;">17</span>                 transactedInstaller.Install(<span style="color: #0000ff;">new</span><span style="color: #000000;"> System.Collections.Hashtable());
</span><span style="color: #008080;">18</span>                 txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">服务安装成功！</span><span style="color: #800000;">"</span>;            </pre>
</div>
<span class="cnblogs_code_collapse">View Code </span></div>
<p>&nbsp;上面这段代码中最为中要的部分是方法 <span style="color: #2b91af;">GetServiceName</span>，通过给定路径获取服务的名称。下面来看看这个方法是怎么实现的。</p>
<div class="cnblogs_code" onclick="cnblogs_code_show('fd525981-4497-4686-a39c-845f8427bf5d')"><img id="code_img_closed_fd525981-4497-4686-a39c-845f8427bf5d" class="code_img_closed" src="http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt="" /><img id="code_img_opened_fd525981-4497-4686-a39c-845f8427bf5d" class="code_img_opened" style="display: none;" onclick="cnblogs_code_hide('fd525981-4497-4686-a39c-845f8427bf5d',event)" src="http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="" />
<div id="cnblogs_code_open_fd525981-4497-4686-a39c-845f8427bf5d" class="cnblogs_code_hide">
<pre><span style="color: #008080;"> 1</span>  <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
<span style="color: #008080;"> 2</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 获取Windows服务的名称
</span><span style="color: #008080;"> 3</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
<span style="color: #008080;"> 4</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;param name="serviceFileName"&gt;</span><span style="color: #008000;">文件路径</span><span style="color: #808080;">&lt;/param&gt;</span>
<span style="color: #008080;"> 5</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;returns&gt;</span><span style="color: #008000;">服务名称</span><span style="color: #808080;">&lt;/returns&gt;</span>
<span style="color: #008080;"> 6</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">string</span> GetServiceName(<span style="color: #0000ff;">string</span><span style="color: #000000;"> serviceFileName)
</span><span style="color: #008080;"> 7</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 8</span>             <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 9</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">10</span>                 Assembly assembly =<span style="color: #000000;"> Assembly.LoadFrom(serviceFileName);
</span><span style="color: #008080;">11</span>                 Type[] types =<span style="color: #000000;"> assembly.GetTypes();
</span><span style="color: #008080;">12</span>                 <span style="color: #0000ff;">foreach</span> (Type myType <span style="color: #0000ff;">in</span><span style="color: #000000;"> types)
</span><span style="color: #008080;">13</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">14</span>                     <span style="color: #0000ff;">if</span> (myType.IsClass &amp;&amp; myType.BaseType == <span style="color: #0000ff;">typeof</span><span style="color: #000000;">(System.Configuration.Install.Installer))
</span><span style="color: #008080;">15</span> <span style="color: #000000;">                    {
</span><span style="color: #008080;">16</span>                         FieldInfo[] fieldInfos = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Default | BindingFlags.Instance |<span style="color: #000000;"> BindingFlags.Static);
</span><span style="color: #008080;">17</span>                         <span style="color: #0000ff;">foreach</span> (FieldInfo myFieldInfo <span style="color: #0000ff;">in</span><span style="color: #000000;"> fieldInfos)
</span><span style="color: #008080;">18</span> <span style="color: #000000;">                        {
</span><span style="color: #008080;">19</span>                             <span style="color: #0000ff;">if</span> (myFieldInfo.FieldType == <span style="color: #0000ff;">typeof</span><span style="color: #000000;">(System.ServiceProcess.ServiceInstaller))
</span><span style="color: #008080;">20</span> <span style="color: #000000;">                            {
</span><span style="color: #008080;">21</span>                                 ServiceInstaller serviceInstaller =<span style="color: #000000;"> (ServiceInstaller)myFieldInfo.GetValue(Activator.CreateInstance(myType));
</span><span style="color: #008080;">22</span>                                 <span style="color: #0000ff;">return</span><span style="color: #000000;"> serviceInstaller.ServiceName;
</span><span style="color: #008080;">23</span> <span style="color: #000000;">                            }
</span><span style="color: #008080;">24</span> <span style="color: #000000;">                        }
</span><span style="color: #008080;">25</span> <span style="color: #000000;">                    }
</span><span style="color: #008080;">26</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">27</span>                 <span style="color: #0000ff;">return</span> <span style="color: #800000;">""</span><span style="color: #000000;">;
</span><span style="color: #008080;">28</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">29</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">30</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">31</span>                 <span style="color: #0000ff;">throw</span><span style="color: #000000;"> ex;
</span><span style="color: #008080;">32</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">33</span>         }</pre>
</div>
<span class="cnblogs_code_collapse">View Code </span></div>
<p>&nbsp;1.加载程序集</p>
<p>&nbsp;2.获取程序集里面继承于System.Configuration.Install.<span style="color: #2b91af;">Installer<span style="color: #000000;">这个类的类，原因在于Windows服务都需要添加一个安装程序，而安装程序是继承这个类的</span></span><span style="color: #2b91af;"><span style="color: #000000;">，</span></span></p>
<p><span style="color: #2b91af;"><span style="color: #000000;">&nbsp;安装以后的服务名称是通过这个类<span style="color: #2b91af;">ServiceInstaller<span style="color: #000000;">的变量指定的，比如ServiceInstaller.ServiceName = "xxx";</span></span></span></span></p>
<p><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;">&nbsp;3.获取第二步<span style="color: #2b91af;">Installer</span>类里面的<span style="color: #2b91af;">ServiceInstaller</span>变量的值，然后获取这个值的ServiceName属性就是服务的名称。</span></span></span></span></p>
<p><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;"><strong>&nbsp;2.运行功能：</strong></span></span></span></span></p>
<div class="cnblogs_code" onclick="cnblogs_code_show('64ebdb41-3cf4-4919-a1fe-0fa6022d77c5')"><img id="code_img_closed_64ebdb41-3cf4-4919-a1fe-0fa6022d77c5" class="code_img_closed" src="http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt="" /><img id="code_img_opened_64ebdb41-3cf4-4919-a1fe-0fa6022d77c5" class="code_img_opened" style="display: none;" onclick="cnblogs_code_hide('64ebdb41-3cf4-4919-a1fe-0fa6022d77c5',event)" src="http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="" />
<div id="cnblogs_code_open_64ebdb41-3cf4-4919-a1fe-0fa6022d77c5" class="cnblogs_code_hide">
<pre><span style="color: #008080;"> 1</span> <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 2</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 3</span>                 <span style="color: #0000ff;">string</span> serviceName =<span style="color: #000000;"> GetServiceName(txtPath.Text.Trim());
</span><span style="color: #008080;"> 4</span>                 <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">string</span><span style="color: #000000;">.IsNullOrEmpty(serviceName))
</span><span style="color: #008080;"> 5</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 6</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">指定文件不是Windows服务！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;"> 7</span>                     <span style="color: #0000ff;">return</span><span style="color: #000000;">;
</span><span style="color: #008080;"> 8</span> <span style="color: #000000;">                }
</span><span style="color: #008080;"> 9</span>                 <span style="color: #0000ff;">if</span> (!<span style="color: #000000;">ServiceIsExisted(serviceName))
</span><span style="color: #008080;">10</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">11</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">要运行的服务不存在！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">12</span>                     <span style="color: #0000ff;">return</span><span style="color: #000000;">;
</span><span style="color: #008080;">13</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">14</span>                 ServiceController service = <span style="color: #0000ff;">new</span><span style="color: #000000;"> ServiceController(serviceName);
</span><span style="color: #008080;">15</span>                 <span style="color: #0000ff;">if</span> (service.Status != ServiceControllerStatus.Running &amp;&amp; service.Status !=<span style="color: #000000;"> ServiceControllerStatus.StartPending)
</span><span style="color: #008080;">16</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">17</span> <span style="color: #000000;">                    service.Start();
</span><span style="color: #008080;">18</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">服务运行成功！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">19</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">20</span>                 <span style="color: #0000ff;">else</span>
<span style="color: #008080;">21</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">22</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">服务正在运行！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">23</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">24</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">25</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">26</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">27</span>                 txtTip.Text =<span style="color: #000000;"> ex.InnerException.ToString();
</span><span style="color: #008080;">28</span>             }</pre>
</div>
<span class="cnblogs_code_collapse">View Code </span></div>
<p><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;">重要的是<span style="color: #2b91af;">ServiceController</span>这个类，这个类可以获取系统中所有的服务</span></span></span></span></p>
<div class="cnblogs_code" onclick="cnblogs_code_show('a43c4a11-10c8-4577-aef3-487e4c860e65')"><img id="code_img_closed_a43c4a11-10c8-4577-aef3-487e4c860e65" class="code_img_closed" src="http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt="" /><img id="code_img_opened_a43c4a11-10c8-4577-aef3-487e4c860e65" class="code_img_opened" style="display: none;" onclick="cnblogs_code_hide('a43c4a11-10c8-4577-aef3-487e4c860e65',event)" src="http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="" />
<div id="cnblogs_code_open_a43c4a11-10c8-4577-aef3-487e4c860e65" class="cnblogs_code_hide">
<pre><span style="color: #008080;"> 1</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;summary&gt;</span>
<span style="color: #008080;"> 2</span>         <span style="color: #808080;">///</span><span style="color: #008000;"> 判断服务是否已经存在
</span><span style="color: #008080;"> 3</span>      <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;/summary&gt;</span>
<span style="color: #008080;"> 4</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;param name="serviceName"&gt;</span><span style="color: #008000;">服务名称</span><span style="color: #808080;">&lt;/param&gt;</span>
<span style="color: #008080;"> 5</span>         <span style="color: #808080;">///</span> <span style="color: #808080;">&lt;returns&gt;</span><span style="color: #008000;">bool</span><span style="color: #808080;">&lt;/returns&gt;</span>
<span style="color: #008080;"> 6</span>         <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">bool</span> ServiceIsExisted(<span style="color: #0000ff;">string</span><span style="color: #000000;"> serviceName)
</span><span style="color: #008080;"> 7</span> <span style="color: #000000;">        {
</span><span style="color: #008080;"> 8</span>             ServiceController[] services =<span style="color: #000000;"> ServiceController.GetServices();
</span><span style="color: #008080;"> 9</span>             <span style="color: #0000ff;">foreach</span> (ServiceController s <span style="color: #0000ff;">in</span><span style="color: #000000;"> services)
</span><span style="color: #008080;">10</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">11</span>                 <span style="color: #0000ff;">if</span> (s.ServiceName ==<span style="color: #000000;"> serviceName)
</span><span style="color: #008080;">12</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">13</span>                     <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #000000;">;
</span><span style="color: #008080;">14</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">15</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">16</span>             <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #000000;">;
</span><span style="color: #008080;">17</span>         }</pre>
</div>
<span class="cnblogs_code_collapse">View Code </span></div>
<p><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;"><strong>&nbsp;3.停止功能：</strong></span></span></span></span></span></span></span></span></p>
<div class="cnblogs_code" onclick="cnblogs_code_show('d3037e40-d4cb-48ed-b444-f0845a325d61')"><img id="code_img_closed_d3037e40-d4cb-48ed-b444-f0845a325d61" class="code_img_closed" src="http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt="" /><img id="code_img_opened_d3037e40-d4cb-48ed-b444-f0845a325d61" class="code_img_opened" style="display: none;" onclick="cnblogs_code_hide('d3037e40-d4cb-48ed-b444-f0845a325d61',event)" src="http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="" />
<div id="cnblogs_code_open_d3037e40-d4cb-48ed-b444-f0845a325d61" class="cnblogs_code_hide">
<pre><span style="color: #008080;"> 1</span> <span style="color: #000000;">ry
</span><span style="color: #008080;"> 2</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 3</span>                 <span style="color: #0000ff;">string</span>[] cmdline =<span style="color: #000000;"> { };
</span><span style="color: #008080;"> 4</span>                 <span style="color: #0000ff;">string</span> serviceFileName =<span style="color: #000000;"> txtPath.Text.Trim();
</span><span style="color: #008080;"> 5</span>                 <span style="color: #0000ff;">string</span> serviceName =<span style="color: #000000;"> GetServiceName(serviceFileName);
</span><span style="color: #008080;"> 6</span>                 <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">string</span><span style="color: #000000;">.IsNullOrEmpty(serviceName))
</span><span style="color: #008080;"> 7</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 8</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">指定文件不是Windows服务！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;"> 9</span>                     <span style="color: #0000ff;">return</span><span style="color: #000000;">;
</span><span style="color: #008080;">10</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">11</span>                 <span style="color: #0000ff;">if</span> (!<span style="color: #000000;">ServiceIsExisted(serviceName))
</span><span style="color: #008080;">12</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">13</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">要停止的服务不存在！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">14</span>                     <span style="color: #0000ff;">return</span><span style="color: #000000;">;
</span><span style="color: #008080;">15</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">16</span>                 ServiceController service = <span style="color: #0000ff;">new</span><span style="color: #000000;"> ServiceController(serviceName);
</span><span style="color: #008080;">17</span>                 <span style="color: #0000ff;">if</span> (service.Status ==<span style="color: #000000;"> ServiceControllerStatus.Running)
</span><span style="color: #008080;">18</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">19</span> <span style="color: #000000;">                    service.Stop();
</span><span style="color: #008080;">20</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">服务停止成功！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">21</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">22</span>                 <span style="color: #0000ff;">else</span>
<span style="color: #008080;">23</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">24</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">服务已经停止！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">25</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">26</span> 
<span style="color: #008080;">27</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">28</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">29</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">30</span>                 txtTip.Text =<span style="color: #000000;"> ex.InnerException.ToString();
</span><span style="color: #008080;">31</span>             }</pre>
</div>
<span class="cnblogs_code_collapse">View Code </span></div>
<p><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;"><span style="color: #2b91af;"><span style="color: #000000;"><strong>4.卸载功能：</strong></span></span></span></span></span></span></span></span></p>
<div class="cnblogs_code" onclick="cnblogs_code_show('c6df18ad-d74a-48cb-9836-212424753b10')"><img id="code_img_closed_c6df18ad-d74a-48cb-9836-212424753b10" class="code_img_closed" src="http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" alt="" /><img id="code_img_opened_c6df18ad-d74a-48cb-9836-212424753b10" class="code_img_opened" style="display: none;" onclick="cnblogs_code_hide('c6df18ad-d74a-48cb-9836-212424753b10',event)" src="http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif" alt="" />
<div id="cnblogs_code_open_c6df18ad-d74a-48cb-9836-212424753b10" class="cnblogs_code_hide">
<pre><span style="color: #008080;"> 1</span>  <span style="color: #0000ff;">try</span>
<span style="color: #008080;"> 2</span> <span style="color: #000000;">            {
</span><span style="color: #008080;"> 3</span>                 <span style="color: #0000ff;">string</span>[] cmdline =<span style="color: #000000;"> { };
</span><span style="color: #008080;"> 4</span>                 <span style="color: #0000ff;">string</span> serviceFileName =<span style="color: #000000;"> txtPath.Text.Trim();
</span><span style="color: #008080;"> 5</span>                 <span style="color: #0000ff;">string</span> serviceName =<span style="color: #000000;"> GetServiceName(serviceFileName);
</span><span style="color: #008080;"> 6</span>                 <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">string</span><span style="color: #000000;">.IsNullOrEmpty(serviceName))
</span><span style="color: #008080;"> 7</span> <span style="color: #000000;">                {
</span><span style="color: #008080;"> 8</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">指定文件不是Windows服务！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;"> 9</span>                     <span style="color: #0000ff;">return</span><span style="color: #000000;">;
</span><span style="color: #008080;">10</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">11</span>                 <span style="color: #0000ff;">if</span> (!<span style="color: #000000;">ServiceIsExisted(serviceName))
</span><span style="color: #008080;">12</span> <span style="color: #000000;">                {
</span><span style="color: #008080;">13</span>                     txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">要卸载的服务不存在！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">14</span>                     <span style="color: #0000ff;">return</span><span style="color: #000000;">;
</span><span style="color: #008080;">15</span> <span style="color: #000000;">                }
</span><span style="color: #008080;">16</span>                 TransactedInstaller transactedInstaller = <span style="color: #0000ff;">new</span><span style="color: #000000;"> TransactedInstaller();
</span><span style="color: #008080;">17</span>                 AssemblyInstaller assemblyInstaller = <span style="color: #0000ff;">new</span><span style="color: #000000;"> AssemblyInstaller(serviceFileName, cmdline);
</span><span style="color: #008080;">18</span> <span style="color: #000000;">                transactedInstaller.Installers.Add(assemblyInstaller);
</span><span style="color: #008080;">19</span>                 transactedInstaller.Uninstall(<span style="color: #0000ff;">null</span><span style="color: #000000;">);
</span><span style="color: #008080;">20</span>                 txtTip.Text = <span style="color: #800000;">"</span><span style="color: #800000;">服务卸载成功！</span><span style="color: #800000;">"</span><span style="color: #000000;">;
</span><span style="color: #008080;">21</span> 
<span style="color: #008080;">22</span> <span style="color: #000000;">            }
</span><span style="color: #008080;">23</span>             <span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
</span><span style="color: #008080;">24</span> <span style="color: #000000;">            {
</span><span style="color: #008080;">25</span>                 txtTip.Text =<span style="color: #000000;"> ex.InnerException.ToString();
</span><span style="color: #008080;">26</span>             }</pre>
</div>
<span class="cnblogs_code_collapse">View Code </span></div>
<p>&nbsp;</p>
<h1 style="background-color: #a5a5a5; color: white; font-size: 22px;">总结</h1>
<p>1.整体来说实现了服务的整个功能，可以方便的运行停止服务，而不再是使用命令行的方式。</p>
<p>2.下一篇将讲解，使用Windows服务实现任务处理（及定时执行某个功能）。</p>
<p>&nbsp;</p>
<div class="articleFooter">
<p> 如果，您认为阅读这篇博客让您有些收获，不妨点击一下右下角的<a id="btnRecommendMyBlog" href="javascript:void(0);">【<strong>推荐</strong>】</a>按钮。<br />
如果，您希望更容易地发现我的新博客，不妨点击一下绿色通道的<a onclick="c_follow();" href="javascript:void(0);">【<strong>关注我</strong>】</a>。<br />
因为，我的写作热情也离不开您的肯定支持。
</p>
<p>感谢您的阅读，如果您对我的博客所讲述的内容有兴趣，请继续关注我的后续博客，我是焰尾迭 。</p>





</div></div><div id="MySignature"></div>
<div class="clear"></div>
<div id="blog_post_info_block">
<div id="BlogPostCategory"></div>
<div id="EntryTag"></div>
<div id="blog_post_info">
</div>
<div class="clear"></div>
<div id="post_next_prev"></div>
</div>


	<div class="postDesc">posted on <span id="post-date">2014-02-10 14:31</span> <a href='http://www.cnblogs.com/yanweidie/'>焰尾迭</a> 阅读(<span id="post_view_count">...</span>) 评论(<span id="post_comment_count">...</span>)  <a href ="http://i.cnblogs.com/EditPosts.aspx?postid=3542670" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(3542670);return false;">收藏</a></div>
</div>
<script type="text/javascript">var allowComments=true,isLogined=false,cb_blogId=114902,cb_entryId=3542670,cb_blogApp=currentBlogApp,cb_blogUserGuid='91ae0150-efe9-e011-8ee0-842b2b196315',cb_entryCreatedDate='2014/2/10 14:31:00';loadViewCount(cb_entryId);</script>

</div><a name="!comments"></a><div id="blog-comments-placeholder"></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
<div id='comment_form' class='commentform'>
<a name='commentform'></a>
<div id='divCommentShow'></div>
<div id='comment_nav'><span id='span_refresh_tips'></span><a href='javascript:void(0);' onclick='return RefreshCommentList();' id='lnk_RefreshComments' runat='server' clientidmode='Static'>刷新评论</a><a href='#' onclick='return RefreshPage();'>刷新页面</a><a href='#top'>返回顶部</a></div>
<div id='comment_form_container'></div>
<div class='ad_text_commentbox' id='ad_text_under_commentbox'></div>
<div id='ad_t2'></div>
<div id='opt_under_post'></div>
<div id='ad_c1' class='c_ad_block'></div>
<div id='under_post_news'></div>
<div id='under_post_kb'></div>
<div id='HistoryToday' class='c_ad_block'></div>
<script type='text/javascript'>
$(function () {
    setTimeout(function () { incrementViewCount(cb_entryId); }, 50);
    deliverAdT2();
    deliverAdC1();    
    loadNewsAndKb();
    loadBlogSignature();
    LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
    GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate);
    loadOptUnderPost();
    GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);    
});
</script>
</div>


		</div>
	</div>
	<!-- left ends -->
	<!-- right starts -->
	<div id="right">
		<!-- 右侧工具部分 -->
		<div id="right_content">
	
			
<!--done-->
<h2 class="listtitle">公告</h2>
<div class="newsItem">
	<div id="blog-news"></div><script type="text/javascript">loadBlogNews();</script>
</div>

	
			<div id="calendar"><div id="blog-calendar" style="display:none"></div><script type="text/javascript">loadBlogDefaultCalendar();</script></div>
			
				<DIV id="leftcontentcontainer">
					<div id="blog-sidecolumn"></div><script type="text/javascript">loadBlogSideColumn();</script>
				</DIV>
			
		</div>
		<!-- //右侧工具部分 -->
		<div id="footer">
			
<!--done-->
Copyright &copy;2016 焰尾迭
		</div>
	</div>
	<!-- right ends -->
	<div class="clear"></div>
	
</div>

</body>
</html>
